package com.salt.modules.sys.web;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.salt.common.beanvalidator.BeanValidators;
import com.salt.common.json.AjaxJson;
import com.salt.common.utils.DateUtils;
import com.salt.common.utils.StringUtils;
import com.salt.common.utils.excel.ExportExcelDataList;
import com.salt.common.utils.excel.ImportExcelDataList;
import com.salt.core.log.annotation.OperationRecord;
import com.salt.core.oss.OssTemplate;
import com.salt.core.oss.model.SaltFile;
import com.salt.core.persistence.Page;
import com.salt.core.web.BaseController;
import com.salt.modules.sys.entity.*;
import com.salt.modules.sys.security.util.JWTUtil;
import com.salt.modules.sys.service.*;
import com.salt.modules.sys.utils.DictUtils;
import com.salt.modules.sys.utils.MenuUtils;
import com.salt.modules.sys.utils.RouterUtils;
import com.salt.modules.sys.utils.UserUtils;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FilenameUtils;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import java.io.IOException;
import java.util.*;

/**
 * 用户Controller
 * @author salt
 * @version 2016-8-29
 */
@RestController
@RequestMapping("/sys/user")
public class UserController extends BaseController {
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private OssTemplate ossTemplate;
    @Autowired
    private OfficeService officeService;
    @Autowired
    private MultiTenantService multiTenantService;
    @Autowired
    private LoginService loginService;
    @Autowired
    private CompanyService companyService;


    @ModelAttribute
    public User get(@RequestParam(required = false) String id) {
        if (StringUtils.isNotBlank(id)) {
            User user = userService.get(id);
            if (user != null) {
                if (StringUtils.isNotBlank(user.getPhoto())) {
                    user.setPhoto(ossTemplate.outerFileLink(user.getPhoto()));
                }
                if (StringUtils.isNotBlank(user.getSign())) {
                    user.setSign(ossTemplate.outerFileLink(user.getSign()));
                }
            }
            return user;
        } else {
            return new User();
        }
    }

    @GetMapping("currUser")
    public AjaxJson currUser() {
        User user = userService.get(UserUtils.getUser().getId());
        if (user.getOffice() != null && StringUtils.isNotBlank(user.getOffice().getId()))
            user.setOffice(officeService.get(user.getOffice().getId()));
        if (StringUtils.isNotBlank(user.getSign())) {
            user.setSign(ossTemplate.outerFileLink(user.getSign()));
        }
        return AjaxJson.success().put("currUser", user);
    }

    @GetMapping("getCurrLoginUser")
    public AjaxJson getCurrLoginUser() {
        return AjaxJson.success().put("user", UserUtils.getUser());
    }

    @RequiresPermissions(value = {"sys:user:view", "sys:user:add", "sys:user:edit"}, logical = Logical.OR)
    @GetMapping("queryById")
    public AjaxJson queryById(User user) {
        return AjaxJson.success().put("user", user);
    }

    //@RequiresPermissions("sys:user:list")
    @GetMapping("list")
    public AjaxJson list(User user, HttpServletRequest request, HttpServletResponse response) {
        User currUser = UserUtils.getUser();
        if (!(user.getOffice() != null && StringUtils.isNotBlank(user.getOffice().getId())) &&
                !(user.getCompany() != null && StringUtils.isNotBlank(user.getCompany().getId()))) {
            if (!currUser.isAdmin()) { // 是不是超级管理员
                MultiTenant multiTenant = multiTenantService.find(new MultiTenant(currUser));
                if (multiTenant != null) {  // 是不是具有多租户权限
                    user.setTenantIds(multiTenant.getTenanIds());
                } else {  // 不是超级管理员也不具有租户权限
                    user.setCompany(currUser.getCompany());
                }
            }
        }
        Page<User> page = userService.findPage(new Page<User>(request, response), user);

        String systemType = loginService.getCachLoginSystemType(currUser.getId());

        return AjaxJson.success().put("page", page).put("systemType", systemType);
    }

    @OperationRecord(service = "系统服务", module = "用户管理", operation = "新增/修改", description = "新增/修改用户")
    @RequiresPermissions(value = {"sys:user:add", "sys:user:edit"}, logical = Logical.OR)
    @PostMapping("save")
    public AjaxJson save(User user) {
        if (saltProperites.isDemoMode()) {
            return AjaxJson.error("演示模式，不允许操作!");
        }
        // 如果新密码为空，则不更换密码
        if (StringUtils.isNotBlank(user.getNewPassword())) {
            user.setPassword(userService.entryptPassword(user.getNewPassword()));
        }
        /**
         * 后台hibernate-validation插件校验
         */
        String errMsg = beanValidator(user);
        if (StringUtils.isNotBlank(errMsg)) {
            return AjaxJson.error(errMsg);
        }
        if (!isCheckLoginName(user.getOldLoginName(), user.getLoginName())) {
            return AjaxJson.error("保存用户'" + user.getLoginName() + "'失败，登录名已存在!");
        }
        // 角色数据有效性验证，过滤不在授权内的角色
        List<Role> roleList = Lists.newArrayList();
        List<String> roleIdList = user.getRoleIdList();
        for (String roleId : roleIdList) {
            roleList.add(roleService.get(roleId));
        }
        user.setRoleList(roleList);

        // 当修改用户信息时，删除文件服务器上用户之前当头像
        /*if (StringUtils.isNotBlank(user.getId())) {
            User oldUser = userService.get(user.getId());
            if (StringUtils.isNotBlank(oldUser.getPhoto())) {
                ossTemplate.removeFile(oldUser.getPhoto());
            }
        }*/

        if (StringUtils.isNotBlank(user.getPhoto())) {
            String[] split = user.getPhoto().split("/", 5);
            user.setPhoto(split[4]);
        }

        if (StringUtils.isNotBlank(user.getSign())) {
            String[] split = user.getSign().split("/", 5);
            user.setSign(split[4]);
        }

        // TODO 添加用户公司信息
        /*if (user.getCompany() != null) {
            User user1 = new User();
            user1.setCompany(user.getCompany());
            List<User> userList = userService.findListByOffice(user1);
            if (userList != null && userList.get(0).getCompany1() != null)
                user.setCompany1(userList.get(0).getCompany1());
        }*/

        // 保存用户信息
        userService.saveUser(user);
        // 清除当前用户缓存
        if (user.getLoginName().equals(UserUtils.getUser().getLoginName())) {
            UserUtils.clearCache();
        }
        return AjaxJson.success("保存用户'" + user.getLoginName() + "'成功!");
    }

    /**
     * 批量删除用户
     */
    @ApiOperation(value = "删除用户")
    @OperationRecord(service = "系统服务", module = "用户管理", operation = "删除", description = "删除用户")
    @RequiresPermissions("sys:user:del")
    @DeleteMapping("delete")
    public AjaxJson delete(String ids) {
        String idArray[] = ids.split(",");
        AjaxJson j = new AjaxJson();
        if (saltProperites.isDemoMode()) {
            return AjaxJson.error("演示模式，不允许操作!");
        }
        StringBuffer msg = new StringBuffer();
        boolean success = true;
        List<String> fileNames = new LinkedList<>();
        for (String id : idArray) {
            User user = userService.get(id);
            if (UserUtils.getUser().getId().equals(user.getId())) {
                success = false;
                msg.append("["+user.getLoginName()+"]删除失败，不允许删除当前用户!<br/>");
            } else if (User.isAdmin(user.getId())) {
                success = false;
                msg.append("["+user.getLoginName()+"]删除失败，不允许删除超级管理员!<br/>");//删除用户失败, 不允许删除超级管理员用户
            } else {
                msg.append("["+user.getLoginName()+"]删除成功!<br/>");
                userService.deleteUser(user);//删除用户成功
                // 将photo存入集合中
                if(StringUtils.isNotBlank(user.getPhoto())) {
                    fileNames.add(user.getPhoto());
                }
            }
        }
        // 删除用户时删除文件服务中当头像
        /*if (!fileNames.isEmpty()) {
            ossTemplate.removeFiles(fileNames);
        }*/
        if(success){
            return AjaxJson.success(msg.toString());
        }else {
            return AjaxJson.error(msg.toString());
        }
    }

    /**
     * 导出用户数据
     *
     * @param user
     * @param request
     * @param response
     * @return
     */
    //@RequiresPermissions("sys:user:export")
    @GetMapping("export")
    @OperationRecord(service = "系统服务", module = "用户管理", operation = "导出", description = "导出用户")
    public void exportFile(User user, HttpServletRequest request, HttpServletResponse response) throws Exception {
        String fileName = "用户数据" + DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";
        Page<User> page = userService.findPage(new Page<User>(request, response, -1), user);
        new ExportExcelDataList("用户数据", User.class).setDataList(page.getList()).write(response, fileName).dispose();
    }

    /**
     * 导入用户数据
     *
     * @param file
     * @param redirectAttributes
     * @return
     */
    //@RequiresPermissions("sys:user:import")
    @PostMapping("import")
    @OperationRecord(service = "系统服务", module = "用户管理", operation = "导入", description = "导入用户")
    public AjaxJson importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
        if (saltProperites.isDemoMode()) {
            return AjaxJson.error("演示模式，不允许操作！");
        }
        try {
            int successNum = 0;
            int failureNum = 0;
            StringBuilder failureMsg = new StringBuilder();
            ImportExcelDataList ei = new ImportExcelDataList(file, 1, 0);
            List<User> list = ei.getDataList(User.class);
            for (User user : list) {
                try {
                    if (isCheckLoginName("", user.getLoginName())) {
                        user.setPassword(userService.entryptPassword("123456"));
                        BeanValidators.validateWithException(validator, user);
                        userService.saveUser(user);
                        successNum++;
                    } else {
                        failureMsg.append("<br/>登录名 " + user.getLoginName() + " 已存在; ");
                        failureNum++;
                    }
                } catch (ConstraintViolationException ex) {
                    failureMsg.append("<br/>登录名 " + user.getLoginName() + " 导入失败：");
                    List<String> messageList = BeanValidators.extractPropertyAndMessageAsList(ex, ": ");
                    for (String message : messageList) {
                        failureMsg.append(message + "; ");
                        failureNum++;
                    }
                } catch (Exception ex) {
                    failureNum++;
                    failureMsg.append("<br/>登录名 " + user.getLoginName() + " 导入失败：" + ex.getMessage());
                }
            }
            if (failureNum > 0) {
                failureMsg.insert(0, "，失败 " + failureNum + " 条用户，导入信息如下：");
            }
            return AjaxJson.success("已成功导入 " + successNum + " 条用户" + failureMsg);
        } catch (Exception e) {
            return AjaxJson.error("导入用户失败！失败信息：" + e.getMessage());
        }
    }

    /**
     * 下载导入用户数据模板
     *
     * @param response
     * @return
     */
    //@RequiresPermissions("sys:user:import")
    @GetMapping("import/template")
    public AjaxJson importFileTemplate(HttpServletResponse response) {
        try {
            String fileName = "用户数据导入模板.xlsx";
            List<User> list = Lists.newArrayList();
            list.add(UserUtils.getUser());
            new ExportExcelDataList("用户数据", User.class, 2).setDataList(list).write(response, fileName).dispose();
            return null;
        } catch (Exception e) {
            return AjaxJson.error("导入模板下载失败！失败信息：" + e.getMessage());
        }
    }



    private boolean isCheckLoginName(String oldLoginName, String loginName) {
        if (loginName != null && loginName.equals(oldLoginName)) {
           return true;
        } else if (loginName != null && userService.getUserByLoginName(loginName) == null) {
            return true;
        }
      return false;
    }


    /**
     * 用户信息显示编辑保存
     *
     * @param user
     * @return
     */
    @RequiresPermissions("sys")
    @PostMapping("saveInfo")
    @OperationRecord(service = "系统服务", module = "用户管理", operation = "编辑", description = "修改个人资料成功")
    public AjaxJson infoEdit(User user) {
        User currentUser = UserUtils.getUser();
        if (saltProperites.isDemoMode()) {
            return AjaxJson.error("演示模式，不允许操作！");
        }
        if (user.getName() != null)
            currentUser.setName(user.getName());
        if (user.getEmail() != null)
            currentUser.setEmail(user.getEmail());
        if (user.getPhone() != null)
            currentUser.setPhone(user.getPhone());
        if (user.getMobile() != null)
            currentUser.setMobile(user.getMobile());
        if (user.getRemarks() != null)
            currentUser.setRemarks(user.getRemarks());
        /*if (user.getSign() != null)
            currentUser.setSign(user.getSign());*/
        if (StringUtils.isNotBlank(user.getSign())) {
            String[] split = user.getSign().split("/", 5);
            user.setSign(split[4]);
        }
        userService.updateUserInfo(currentUser);
        return AjaxJson.success("修改个人资料成功!");
    }


    /**
     * 用户头像显示编辑保存
     *
     * @return
     * @throws IOException
     * @throws IllegalStateException
     */
    //@RequiresPermissions("user")
    @PostMapping("imageUpload")
    //@OperationRecord(service = "系统服务", module = "用户管理", operation = "编辑", description = "编辑个人头像")
    public AjaxJson imageUpload(HttpServletRequest request, HttpServletResponse response, MultipartFile file) throws IllegalStateException, IOException {
        User currentUser = UserUtils.getUser();
        String fileLink = "";
        // 判断文件是否为空
        if (!file.isEmpty()) {
            /*if (StringUtils.isNotBlank(currentUser.getPhoto())) {
                ossTemplate.removeFile(currentUser.getPhoto());
            }*/
            SaltFile saltFile = ossTemplate.putFile(file);
            currentUser.setPhoto(saltFile.getName());
            userService.updateUserInfo(currentUser);
            fileLink = ossTemplate.outerFileLink(saltFile.getName());
        }
        return AjaxJson.success("上传成功!").put("path", fileLink);
    }

    /**
     * 返回用户信息
     *
     * @return
     */
    //@RequiresPermissions("user")
    @GetMapping("info")
    public AjaxJson infoData() {
        User user = UserUtils.getUser();
        if (user != null && StringUtils.isNotBlank(user.getPhoto())) {
            user.setPhoto(ossTemplate.outerFileLink(user.getPhoto()));
        }
        if (user != null && StringUtils.isNotBlank(user.getSign())) {
            user.setSign(ossTemplate.outerFileLink(user.getSign()));
        }
        return AjaxJson.success("获取个人信息成功!").put("role", UserUtils.getRoleList()).put("user", user);
    }


    @RequiresPermissions("user")
    @PostMapping("savePwd")
    @OperationRecord(service = "系统服务", module = "用户管理", operation = "编辑", description = "修改密码")
    public AjaxJson savePwd(String oldPassword, String newPassword, Model model) {
        User user = UserUtils.getUser();
        if (StringUtils.isNotBlank(oldPassword) && StringUtils.isNotBlank(newPassword)) {
            if (saltProperites.isDemoMode()) {
                return AjaxJson.error("演示模式，不允许操作！");
            }
            if (UserService.validatePassword(oldPassword, user.getPassword())) {
                userService.updatePasswordById(user.getId(), user.getLoginName(), newPassword);
                return AjaxJson.success("修改密码成功！");
            } else {
                return AjaxJson.error("修改密码失败，旧密码错误！");
            }
        }
        return AjaxJson.error("参数错误！");
    }


    /**
     * 保存签名
     */
    @PostMapping("saveSign")
    @OperationRecord(service = "系统服务", module = "用户管理", operation = "编辑", description = "保存签名")
    public AjaxJson saveSign(User user,MultipartFile file, boolean __ajax, HttpServletResponse response, Model model) throws Exception {
        User currentUser = UserUtils.getUser();
        String fileLink = "";
        if (!file.isEmpty()) {
            String extension = FilenameUtils.getExtension(file.getOriginalFilename());
            if (extension == null || extension.toLowerCase().indexOf("png") == -1) {
                return AjaxJson.error("请选择正确的文件格式，png");
            }
            SaltFile saltFile = ossTemplate.putFile(file);
            currentUser.setSign(saltFile.getName());
            userService.updateUserInfo(currentUser);
            fileLink = ossTemplate.outerFileLink(saltFile.getName());
        }
        return AjaxJson.success("设置签名成功!").put("path", fileLink);
    }

    //@RequiresPermissions("user")
    @GetMapping("treeData")
    public List<Map<String, Object>> treeData(@RequestParam(required = false) String officeId, HttpServletResponse response) {
        List<Map<String, Object>> mapList = Lists.newArrayList();
        List<User> list = userService.findUserByOfficeId(officeId);
        for (int i = 0; i < list.size(); i++) {
            User e = list.get(i);
            Map<String, Object> map = Maps.newHashMap();
            map.put("id", "u_" + e.getId());
            map.put("pId", officeId);
            map.put("name", StringUtils.replace(e.getName(), " ", ""));
            mapList.add(map);
        }
        return mapList;
    }


    /**
     * web端ajax验证手机号是否可以注册（数据库中不存在）
     */
    @ApiOperation("验证手机号")
    @GetMapping("validateMobile")
    public AjaxJson validateMobile(String mobile, HttpServletResponse response, Model model) {
        User user = userService.findUniqueByProperty("mobile", mobile);
        if (user == null) {
            return AjaxJson.success().put("noExist", true);
        } else {
            return AjaxJson.success().put("noExist", false);
        }
    }



    @ApiOperation(value = "用户权限")
    @RequiresPermissions("user")
    @GetMapping("getPermissions")
    public Set<String> getPermissions(Menu menu) {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        String token = UserUtils.getToken();
        String loginName = JWTUtil.getLoginName(token);
        User user = UserUtils.getByLoginName(loginName);
        if (user != null) {
            List<Menu> list = UserUtils.getMenuList(menu);
            for (Menu menuItem : list) {
                if (StringUtils.isNotBlank(menuItem.getPermission())) {
                    // 添加基于Permission的权限信息
                    for (String permission : StringUtils.split(menuItem.getPermission(), ",")) {
                        info.addStringPermission(permission);
                    }
                }
            }
            // 添加用户权限
            info.addStringPermission("user");
            // 添加用户角色信息
            for (Role role : user.getRoleList()) {
                info.addRole(role.getEnname());
            }
        }
        return info.getStringPermissions();
    }


    /*@GetMapping("getMenus")
    @RequiresPermissions("user")
    public AjaxJson getMenus() {
        AjaxJson j = new AjaxJson();
        j.put("dictList", this.getDicts());
        j.put("permissions", this.getPermissions());
        j.put("menuList", MenuUtils.getMenus());
        j.put("routerList", RouterUtils.getRoutersByMenu());
        return j;
    }*/

    /*@GetMapping("getMenus")
    public AjaxJson getMenus(Office office) {
        Map map = multiTenantService.getTenant(office);
        String tenant = (String) map.get("tenant");
        List<String> tenantIds = (List<String>) map.get("tenantIds");
        AjaxJson j = new AjaxJson();
        j.put("dictList", this.getDicts());
        j.put("permissions", this.getPermissions(new Menu(tenant, tenantIds, "2")));
        j.put("menuList", MenuUtils.getMenus(new Menu(tenant, tenantIds, "2")));
        j.put("routerList", RouterUtils.getRoutersByMenu(new Menu(tenant, tenantIds, "2")));
        return j;
    }*/

    @GetMapping("getMenus")
    @RequiresPermissions("user")
    public AjaxJson getMenus(Office office, String clear) {
        long starttime = System.currentTimeMillis();
        // 从缓存中获取用户登录的那个系统
        String loginSystemType = loginService.getCachLoginSystemType(UserUtils.getUser().getId());
        String tenant = null;
        List<String> tenantIds = null;
        // 如果是等录的是3：工业互联网平台，则按多租户获取用户的菜单权限，
        // 如果是 1：双重预防机制系统；和 2：碳排放核查与配额清缴系统；，则不走多租户数据处理，只获取系统分配给用户的菜单权限
        if (Objects.equals(loginSystemType, "3")) {
            Map map = multiTenantService.getTenant(office);
            tenant = (String) map.get("tenant");
            tenantIds = (List<String>) map.get("tenantIds");
        }

        AjaxJson j = new AjaxJson();
        j.put("dictList", this.getDicts());
        // 企业升级后清理菜单缓存
        if (Objects.equals(clear, "1"))
            UserUtils.clearMenuCache();

        j.put("permissions", this.getPermissions(new Menu(tenant, tenantIds, "2")));
        j.put("menuList", MenuUtils.getMenus(new Menu(tenant, tenantIds, "2")));
        j.put("routerList", RouterUtils.getRoutersByMenu(new Menu(tenant, tenantIds, "2")));
        logger.info("获取用户菜单权限路由耗时：{}", System.currentTimeMillis() - starttime);
        return j;
    }



    private Map<String, List<DictValue>> getDicts() {
        return DictUtils.getDictMap();
    }


    @PostMapping("photoUpload")
    public AjaxJson photoUpload(HttpServletRequest request, HttpServletResponse response, MultipartFile file) throws IllegalStateException, IOException {
        AjaxJson j = new AjaxJson();
        // 判断文件是否为空
        if (!file.isEmpty()) {
            SaltFile saltFile = ossTemplate.putFile(file);
            j.put("url", saltFile.getOuterLink());
            //j.put("url", ossTemplate.getImageBase64(saltFile.getName(), Base64Constant.BASE64_FORMAT_PNG));
        }
        return j;
    }

}
